rm(list = ls())

library(tidyverse)
library(lfe)
library(pbapply)

## Load MP data

dat <- readRDS('data/mp_data.rds')  %>%
  filter(vote_abstain_no_show == 0) %>%
  filter(elecper != 8) 

experience_covars <- c('nsdap_member', 
                       'syn_in_gem_bin', 
                       'rel_cath',
                       'veteran_ww1',
                       'veteran_ww2', 
                       'capture_ww2',
                       'soviet_capture',
                       'exile_repressed_combined', 
                       'resistance_member')

experience_covars_labels <- c('NSDAP member', 
                              'Jewish presence',
                              'Catholic',
                              'WW1 Veteran', 
                              'WW2 Veteran',
                              'WW2 POW',
                              'Soviet POW',
                              'Repressed / Exile', 
                              'Resistance')


covars <- c('year_birth', 'gender', 'mandate', 'dualcand', 'closeness_district_categ')

##


mf <-  paste('vote_yes', '~', paste(experience_covars, collapse = "+"),'+', paste(covars, collapse = "+"), ' | elecper + party_fe + state_id | 0 | ags_cluster')

cities <- unique(dat$ags[!is.na(dat$ags)])

merge_df <- dat %>%
  dplyr::select(one_of('ags', 'ags_name')) %>%
  distinct(., .keep_all = T)

## Estimate 

mlist_res <- pblapply(cities, function(c){
  
  m_est <- felm(mf %>% as.formula(),
                data = dat  %>% 
                  filter(ags != c | is.na(ags))) %>%
    broom::tidy() %>%
    filter(term == 'syn_in_gem_bin') %>%
    mutate(excluded_city = c)
  
  return(m_est)
  
}) %>%
  reduce(bind_rows) %>%
  left_join(merge_df, by = c('excluded_city' = 'ags'))


## Plot This 

p1 <- ggplot(mlist_res, aes(x = p.value)) + 
  geom_histogram(binwidth = .001, col = 'black') + 
  theme_bw() + 
  labs(x = 'P-value')

p1 



